//
//  ByMineVC.m
//  mijifen_ios
//
//  Created by 朱凯 on 2017/10/20.
//  Copyright © 2017年 itboye. All rights reserved.
//

#import "ByMineVC.h"

// vc
#import "ByMineSettingVC.h"         // 设置
#import "ByMyOrderVC.h"             // 我的订单
#import "ByScoreBillVC.h"           // 积分账单
#import "ByMyCollectionVC.h"        // 我的收藏
#import "ByMyAttentionShopsVC.h"    // 关注商家
#import "ByMyRedPacketVC.h"         // 我的红包
#import "ByMyCouponsVC.h"           // 我的优惠券
#import "ByMyPetCardVC.h"           // 储值卡

// view
#import "ByViewMineHeader.h"        // 头视图

// cell
#import "ByCellBindOtherApp.h"      // 绑定其它app
#import "ByCellMyOrder.h"           // 订单
#import "ByCellMineNormal.h"        // 普通cell

@interface ByMineVC () <UITableViewDelegate, UITableViewDataSource>


@property (nonatomic, strong) UITableView *table;
@property (nonatomic, strong) ByViewMineHeader *header;
@end

@implementation ByMineVC
{
    BOOL    _isLogin;           // 是否登录（初始化根据数据库中的usermodel，后续根据通知获得）
    NSArray *_orderBadges;      // 订单badge数组
    
    CGFloat _naviBarAlpha;      // 导航栏透明度
}

#pragma mark - view method
- (void)viewDidLoad {
    [super viewDidLoad];
    
    _isLogin = USER != nil;
    _orderBadges = @[@0, @0, @0, @0, @0];
    _naviBarAlpha = 0;
    
    [self createTableView];
    
    // 添加通知
    [self addNotification];

    // 模拟一个通知事件，但不通知其他注册该通知名的控制器
    NSNotification *noti = [NSNotification notificationWithName:KLoginStatusChangeNotificationName object:nil userInfo:@{KLoginStatusChangeNotificationStatusKey : @(_isLogin)}];
    [self loginStatusChange:noti];
    
}
- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    [self setNaviAttributeWithTranslucent:true stateBarLightContent:true];
    
    UIColor *color = [BY_THEME_COLOR colorWithAlphaComponent:_naviBarAlpha];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithColor:color] forBarMetrics:UIBarMetricsDefault];

}
- (void)viewSafeAreaInsetsDidChange {
    
    [super viewSafeAreaInsetsDidChange];
    
    // 为了美观，我们保持header的内容区域为120，其他的部分是导航栏部分（即view的安全区域）
    self.header.height = self.view.safeAreaInsets.top + 120;
}

#pragma mark - 通知事件
// 移除通知
- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
// 添加通知
- (void)addNotification {
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginStatusChange:) name:KLoginStatusChangeNotificationName object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orderBadgeValueChange:) name:KMineOrderBadgeValueChangeNotificationName object:nil];

}
// 登录状态改变
- (void)loginStatusChange:(NSNotification *)noti {
    
    BOOL isLogin = [noti.userInfo[KLoginStatusChangeNotificationStatusKey] boolValue];
    
    NSArray *leftItems, *rightItems;
    if (isLogin) {
        leftItems = @[@"签到"];
        rightItems = @[@"设置"];
    }
    else {
        leftItems = nil;
        rightItems = nil;
    }
    
    // 设置导航栏左右侧item
    [self addBYItemviews:leftItems mode:ByNavigationItemModeImageAndText position:ByNavigationItemPositionModeLeft];
    [self addBYItemviews:rightItems mode:ByNavigationItemModeImageAndText position:ByNavigationItemPositionModeRight];
    // 设置头视图的UI
    _header.isLogin = isLogin;
    // 设置全局的isLogin，并刷新table
    _isLogin = isLogin;
    [_table reloadData];
}
// 订单badge改变
- (void)orderBadgeValueChange:(NSNotification *)noti {
    
    NSArray *badges = noti.userInfo[KMineOrderBadgeValueChangeNotificationBadgesKey];
    _orderBadges = badges;
    [_table reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:1]] withRowAnimation:UITableViewRowAnimationNone];
}

#pragma mark - 懒加载
- (NSArray *)funcTitles1 {
    
    return @[@"积分账单", @"我的收藏", @"关注商家", @"我的红包", @"我的优惠券"];
}
- (NSArray *)funcTitles2 {
    
    return @[@"储值卡", @"客服中心"];
}

#pragma mark - 创建视图
- (void)createTableView {
    
    self.table = [[UITableView alloc] init];
    self.table.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.table.delegate = self;
    self.table.dataSource = self;
    self.table.backgroundColor = BY_BG_COLOR;
    [self.view addSubview:self.table];
    [self.table mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view).insets(UIEdgeInsetsMake(0, 0, 49, 0)).priorityMedium();
        if (@available(iOS 11.0, *)) {
            make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom).offset(-49);
            make.left.equalTo(self.view.mas_safeAreaLayoutGuideLeft);
            make.right.equalTo(self.view.mas_safeAreaLayoutGuideRight);
        }
    }];
    
    self.header = [[ByViewMineHeader alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 64 + 120)];
    self.header.isLogin = _isLogin;
    self.table.tableHeaderView = self.header;
    
    
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 4;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    switch (section) {
        case 0:
            return _isLogin ? 1 : 0;
            break;
        case 1:
            return 1;
            break;
        case 2:
            return 5;
            break;
        case 3:
            return 2;
            break;
        default:
            return 0;
            break;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    // 绑定支付宝和微信
    if (indexPath.section == 0) {
        
        ByCellBindOtherApp *cell = [tableView dequeueReusableCellWithIdentifier:@"bindOtherAppCell"];
        if (!cell) {
            cell = [[ByCellBindOtherApp alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"bindOtherAppCell"];
        }
        cell.bindStatus = @[@NO, @YES];
        return cell;
    }
    // 我的订单
    else if (indexPath.section == 1) {
        
        ByCellMyOrder *cell = [tableView dequeueReusableCellWithIdentifier:@"ByCellMyOrder"];
        if (!cell) {
            cell = [[ByCellMyOrder alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ByCellMyOrder"];
        }
        cell.orderBadges = _orderBadges;
        return cell;
    }
    // 积分账单，我的收藏，关注商家，我的红包，我的优惠券
    else if (indexPath.section == 2) {
        
        ByCellMineNormal *cell = [tableView dequeueReusableCellWithIdentifier:@"normalCell1"];
        if (!cell) {
            cell = [[ByCellMineNormal alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"normalCell1"];
        }
        cell.title = [[self funcTitles1] objectAtIndex:indexPath.row];
        cell.iconImageName = @"右箭头";
        return cell;
    }
    // 储值卡，客服中心
    else if (indexPath.section == 3) {
        
        ByCellMineNormal *cell = [tableView dequeueReusableCellWithIdentifier:@"normalCell2"];
        if (!cell) {
            cell = [[ByCellMineNormal alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"normalCell2"];
        }
        cell.title = [[self funcTitles2] objectAtIndex:indexPath.row];
        cell.iconImageName = @"右箭头";
        return cell;
    }
    
    return [UITableViewCell new];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    switch (indexPath.section) {
        case 0:
            return 100;
            break;
        case 1:
            return 130;
            break;
        case 2:
            return 50;
            break;
        case 3:
            return 50;
            break;
        default:
            return 44;
            break;
    }
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    switch (section) {
        case 0:
            return 0;
            break;
        case 1:
            return 0;
            break;
        case 2:
            return 10;
            break;
        case 3:
            return 10;
            break;
        default:
            return 0;
            break;
    }
    
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return UIView.new;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return UIView.new;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:false];
    
    [ByNotificationHandler mineOrderBadgeValueChange:@[@1, @2, @222, @33, @78856]];

    
    if ([self loginIfOnoff] == false) {
        return;
    }
    if (indexPath.section == 1) {
        [self by_normalPush:[ByMyOrderVC new] hasNavi:true];
    }
    else if (indexPath.section == 2) {
        // 积分账单
        if (indexPath.row == 0) {
            [self by_normalPush:[ByScoreBillVC new] hasNavi:true];
        }
        // 我的收藏
        else if (indexPath.row == 1) {
            [self by_normalPush:[ByMyCollectionVC new] hasNavi:true];
        }
        // 关注商家
        else if (indexPath.row == 2) {
            [self by_normalPush:[ByMyAttentionShopsVC new] hasNavi:true];
        }
        // 我的红包
        else if (indexPath.row == 3) {
            [self by_normalPush:[ByMyRedPacketVC new] hasNavi:true];
        }
        // 我的优惠券
        else if (indexPath.row == 4) {
            [self by_normalPush:[ByMyCouponsVC new] hasNavi:true];
        }
    }
    else if (indexPath.section == 3) {
        // 储值卡
        if (indexPath.row == 0) {
            [self by_normalPush:[ByMyPetCardVC new] hasNavi:true];
        }
    }
    
    

}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    CGFloat offset = scrollView.contentOffset.y;
    
    // 往下拉
    if (offset < 0) {
        self.header.offset = offset;
    }
    // 向上推，要把导航栏的颜色显示
    else {
        CGFloat ratio = offset / 88;
        _naviBarAlpha = MIN(ratio, 0.99);
        _naviBarAlpha = MAX(_naviBarAlpha, 0);
        UIColor *color = [BY_THEME_COLOR colorWithAlphaComponent:_naviBarAlpha];
        [self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithColor:color] forBarMetrics:UIBarMetricsDefault];
    }
}


#pragma mark - 未登录先登录
- (BOOL)loginIfOnoff {
    
    if (!USER) {
        ByLoginVC *vc = [ByLoginVC new];
        ByBaseNaviController *navi = [[ByBaseNaviController alloc] initWithRootViewController:vc];
        [self presentViewController:navi animated:true completion:nil];
        return false;
    } else {
        return true;
    }
}

#pragma mark - 点击事件
- (void)leftItemsAction:(NSInteger)leftIndex {
    
}
- (void)rightItemsAction:(NSInteger)rightIndex {
    
    ByMineSettingVC *vc = [ByMineSettingVC new];
    [self by_normalPush:vc hasNavi:true];
}

@end
